<template>
	<!-- 计划农事 -->
	<view class="content">
		<!-- 标题 -->
		<view class="title">
			<image class="titleIcon" src="/static/index/leftTI.png" mode=""></image>
			农事活动：{{$util.getDictData('produce_husbandry_events',dataInfo.husbandryEvents)}}
		</view>
		<view class="form-item justify-between align-center">
			<view class="left">
				<text class="red">*</text> 执行时间:
			</view>
			<view class="right justify-between align-center">
				<view class="timeTips" @click="show = true">
					{{startTime}}
				</view>
				<image class="rightIcon" src="/static/my/rightJT.png" mode=""></image>
			</view>
		</view>
		<view class="form-item justify-between align-center">
			<view class="left">
				<text class="red">*</text> 耗时:
			</view>
			<view class="right justify-between align-center">
				<input class="takeTime" type="text" v-model="formData.takeTime" placeholder="请输入所需耗时"
					placeholder-style="font-size:1.2rem;text-align:right;color:rgba(153,153,153,0.5);" />/小时
			</view>
		</view>
		<view class="form-item justify-between align-start" @click="show1 = true">
			<view class="left justify-between align-start">
				<view style="white-space: nowrap;">
					投入品:
				</view>
				<view v-if="formData.inputs.length>0" class="center-list">
					<view class="inputs-list-item" v-for="item in formData.inputs">
						{{item.inputName}} * {{item.inputCount}}
						<image @click.stop="deleteInputsFn(item.id)" class="closeIcon"
							src="/subPages/static/my/husbandry/close2.png" mode=""></image>
					</view>
				</view>
			</view>
			<view class="right justify-between align-baseline" @click="show1 = true">
				<view v-if="formData.inputs.length==0" class="inputs">请选择所需投入品</view>
				<image class="rightIcon" src="/static/my/rightJT.png" mode=""></image>
			</view>
		</view>
		<!-- 上传图片 -->
		<view class="img">
			<view class="img-title">
				农事图片：
			</view>
			<view class="upload-item">
				<u-upload class="upload" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
					:maxCount="2" :multiple="true" :width="'220rpx'" :height="'220rpx'">
					<image class="uploadIcon" src="/subPages/static/my/husbandry/upload.png" mode="aspectFill"></image>
				</u-upload>
			</view>
		</view>
		<!-- 确定计划 -->
		<view class="ok" @click="update">
			执行
		</view>
		<!-- 日期时间选择 -->
		<u-datetime-picker :show="show" v-model="formData.startTime" @cancel="show=false" mode="datetime"
			@confirm="confirmFn1">
		</u-datetime-picker>
		<!-- 投入品选择 -->
		<u-popup round="8" :show="show1" mode="center">
			<view class="inputsProp">
				<view class="title">
					<image class="titleIcon" src="/static/index/leftTI.png" mode=""></image>
					投入品选择
				</view>
				<view class="inputsType">
					投入品类型：
					<view class="select-inputsType justify-between align-center" @click="show2 = true"
						:style="{color:inputs.inputName=='请选择投入品类型'?'#999':'#333'}">{{inputs.inputName}}
						<image class="inputsTypeIcon" src="/subPages/static/my/husbandry/bottomJT.png" mode=""></image>
					</view>
				</view>
				<view class="inputsNum">
					投入品数量：
					<u--form labelPosition="left" :model="inputs" :rules="rules" ref="form">
						<u-form-item label="" prop="num">
							<u-input class="inputsNum-input" v-model="inputs.inputCount" type="text"
								placeholder-style="font-size:1.2rem;color:#999;" placeholder="请输入投入品数量" />
						</u-form-item>
					</u--form>
				</view>
				<view class="finish" @click="finishFn">
					确定
				</view>
				<image class="closeIcon" src="/subPages/static/my/husbandry/close.png" @click="closePopupFn" mode="">
				</image>
			</view>
		</u-popup>
		<!-- 投入品类型选择 -->
		<u-picker :show="show2" :columns="inputsTypes" title="投入品类型" keyName="inputName" @confirm="confirmFn2"
			@cancel="show2=false"></u-picker>
	</view>
</template>

<script>
import {timestampToTime} from '@/common/js/util.js'
import {getHusbandryOne, getInputsList, putHusbandryOne} from '@/api/my/husbandry.js'

import {BASE_URL} from '@/common/js/request.js'

export default {
		data() {
			return {
				id: '',
				dataInfo: {},
				show: false,
				startTime: timestampToTime(new Date().getTime()),
				formData: {
					// 执行时间
					startTime: new Date().getTime(),
					// 耗时
					takeTime: '',
					// 投入品类型及数量
					inputs: []
				},
				// 投入品弹出框
				show1: false,
				inputs: {
					id: '',
					inputName: '请选择投入品类型',
					inputCount: '',
				},
				// 投入品类型弹出框
				show2: false,
				inputsTypes: [],
				// 投入品数量校验
				rules: {
					'num': [{
						type: 'number',
						message: '请填写数量',
						trigger: ['blur', 'change']
					}]
				},
				// 上传图片数组
				fileList1: [],
			}
		},
		methods: {
			// 日期确定事件
			confirmFn1(res) {
				this.show = false;
				// 组件会自动修改为时间戳格式 
				this.startTime = timestampToTime(res.value);
				this.formData.startTime = new Date(res.value).getTime();
			},
			// 投入品弹框关闭事件
			closePopupFn() {
				this.show1 = false
				this.show2 = false
			},
			// 投入品选择完成事件
			finishFn() {
				if (this.inputs.inputName == '请选择投入品类型') {
					this.$util.msg('请选择类型')
					return
				}
				if (!this.inputs.inputCount) {
					this.$util.msg('请填写数量')
					return
				}
				this.$refs.form.validate().then(res => {
					if (res) {
						this.$util.msg('添加成功');
					} else {
						this.$util.msg('请检查参数是否正确');
					}
				}).catch((err) => {})
				this.show1 = false;
				let result = this.formData.inputs.find(item => item.id == this.inputs.id);
				if (!result) {
					this.inputs.inputCount = Number(this.inputs.inputCount)
					this.formData.inputs.push(this.inputs);
				} else {
					result.inputCount += Number(this.inputs.inputCount)
				}
				this.inputsTypes = this.inputsTypes.filter(item => item.id != this.inputs.id);
				this.inputs = {
					inputName: '请选择投入品类型',
					inputCount: '',
				}
			},
			// 投入品类型弹框确定事件
			confirmFn2(res) {
				this.show2 = false;
				if (!res.value[0]) {
					return
				}
				this.inputs = res.value[0];
				this.inputs.inputName = res.value[0].inputName || '请选择投入品类型';
				this.inputs.inputCount = '';
			},
			// 删除投入品
			deleteInputsFn(id) {
				this.formData.inputs = this.formData.inputs.filter(v => v.id != id)
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '1',
						url: result
					}))
					fileListLen++
				}
			},
			// 发送上传请求
			uploadFilePromise(url) {
				const authToken = this.$util.getAuthToken();
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: BASE_URL + '/app-api/infra/file/upload',
						filePath: url,
						header: {
							'tenant-id': '1',
							'Authorization': authToken ? `Bearer ${authToken}` : ''
						},
						name: 'file',
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data).data)
							}, 1000)
						}
					});
				})
			},
			// 返回上一页
			toBack() {
				let pages = getCurrentPages();
				let beforePage = pages[pages.length - 1]
				beforePage.initFn()
				beforePage.getHusbandryListFn()
				uni.navigateBack()
			},
			// 获取活动信息
			async getHusbandryOneFn() {
				// 获取当前农事活动的详情
				let res = await getHusbandryOne({
					id: this.id
				});
				this.dataInfo = res;
				res.inputUpdateReqVOS = res.inputUpdateReqVOS.filter((item,index)=>{
					return item.inputName!==null
				})
				// 赋值投入品列表 
				this.formData.inputs = res.inputUpdateReqVOS || [];
				if (this.dataInfo.husbandryImg) {
					this.fileList1 =this.dataInfo.husbandryImg.split(',').map(item=>{
						return {url:item}
					}) 
				}
				// 获取投入品
				let res2 = await getInputsList({
					// inputType: res.inputType,
					pageNo: 1,
					pageSize: 100
				});
				this.inputsTypes = [res2.list];
			},
			async update() {
				if (!this.fileList1.every(v => v.status == 'success')) {
					this.$util.msg('图片未上传完')
					return
				}
				if (!this.formData.takeTime) {
					this.$util.msg('请填写耗时');
					return
				}
				this.fileList1 = this.fileList1.map(item => {
					return item.url
				})
				let res = await putHusbandryOne({
					id: Number(this.id),
					executeStatus: 0, // 执行状态
					executeTime: this.formData.startTime, // 执行时间
					take: Number(this.formData.takeTime), // 耗时
					inputUpdateReqVOS: this.formData.inputs.length === 0 ? null : this.formData.inputs, // 投入品
					husbandryImg: this.fileList1.join(',') // 图片
				});
				if (res) {
					this.$util.msg('执行成功')
					uni.redirectTo({
						url: '/subPages/my/husbandry/index'
					})
				} else {
					this.$util.msg('执行失败')
				}
			}
		},
		onLoad(options) {
			this.id = options.id
			this.getHusbandryOneFn()
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		padding: 2rem 1rem 0;
		font-size: 1.4rem;

		.title {
			display: flex;
			align-items: center;
			font-weight: bold;
			color: #333;

			.titleIcon {
				height: 1.5rem;
				width: .5rem;
				margin-right: .5rem;
			}
		}

		.form-item {
			margin-top: 1.5rem;
			padding-bottom: .5rem;
			line-height: 3.5rem;
			border-bottom: .1rem solid rgba(153, 153, 153, 0.1);
			color: #858A94;

			.red {
				color: #CD292A;
			}

			.timeTips {
				font-size: 1.2rem;
			}

			.rightIcon {
				margin: 1.15rem 0;
				width: 1.2rem;
				height: 1.2rem;
			}

			.takeTime {
				width: 10rem;
				font-size: 1.2rem;
				text-align: right;
				color: #333;
			}

			.inputs {
				width: 10rem;
				height: 2rem;
				font-size: 1.2rem;
				text-align: right;
				color: rgba(153, 153, 153, 0.5);
			}

			.center-list {
				display: flex;
				flex-flow: wrap;

				.inputs-list-item {
					position: relative;
					color: #333;
					height: 2.5rem;
					padding: 0 .5rem;
					background: #ddd;
					border-radius: .4rem;
					text-align: center;
					line-height: 2.5rem;
					margin: .5rem;

					.closeIcon {
						width: 1rem;
						height: 1rem;
						position: absolute;
						top: 0;
						right: 0;
						transform: translate(10%, -10%);
					}
				}
			}
		}

		// 上传图片
		.img {
			margin-top: 1.5rem;
			color: #858A94;

			.upload-item {
				margin-top: 1rem;

				.upload {
					/deep/ .u-upload__wrap__preview {
						height: 220rpx;
						width: 220rpx;
						border-radius: .5rem;
					}
					.uploadIcon{
						height: 220rpx;
						width: 220rpx;
					}
				}
			}
		}

		//确定
		.ok {
			margin: 2.5rem 1rem 0;
			height: 4rem;
			line-height: 4rem;
			text-align: center;
			color: #fff;
			background: linear-gradient(97deg, #74AA61 0%, #53936C 100%);
			border-radius: 2rem
		}

		// 选择日期
		.calendar {
			height: 25rem;
		}

		// 选择投入品
		.inputsProp {
			position: relative;
			width: 23.5rem;
			background: #FFFFFF;
			border-radius: .8rem;
			padding: 2.5rem 1.5rem;

			.inputsType {
				color: #333333;
				margin-top: 1.5rem;

				.select-inputsType {
					font-size: 1.2rem;
					margin-top: .5rem;
					color: #999999;
					width: 20rem;
					height: 3rem;
					padding: 0 1rem;
					background: rgba(153, 153, 153, 0.1);

					.inputsTypeIcon {
						width: 1.2rem;
						height: 1.2rem;
					}
				}
			}

			.inputsNum {
				margin-top: 1.5rem;

				.inputsNum-input {
					width: 20rem;
					height: 3rem;
					background: rgba(153, 153, 153, 0.1);
					border-radius: .4rem;
					font-size: 1.2rem;
					padding-left: 1rem
				}
			}

			.finish {
				margin: .75rem 0 0;
				text-align: center;
			}

			.closeIcon {
				position: absolute;
				top: 0;
				right: 0;
				transform: translate(10%, -10%);
				width: 1.8rem;
				height: 1.8rem;
			}
		}
	}
</style>
